//
//  FlyBaseViewController.m
//  PartyBuildingCloud
//
//  Created by lifayu on 16/9/20.
//  Copyright © 2016年 贵阳飞云科技有限公司. All rights reserved.
//

#import "FlyBaseViewController.h"
#import "EJSAppDelegate.h"
#import "EJSLoginViewController.h"

@interface FlyBaseViewController ()
{
    UIView *_loadingView;
    
    UIImageView *_loadingImgView;
    
    UILabel *_loadingLabel;
    
    
    UIView *_noDataView;
}

@end

@implementation FlyBaseViewController

+ (instancetype)viewController
{
    return nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self setupForDismissKeyboard];
    self.view.backgroundColor = kWhiteColor;
    if(self.navigationController.viewControllers.count > 1)
    {
        [self configNavigationLeftItemWithImage:nil];
    }
    [self configOwnViews];
}

- (void)configOwnViews
{
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.backgroundColor = kWhiteColor;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:UIColorFromRGB(0x3C4151)};
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideTipView) object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)setupForDismissKeyboard
{
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)];
    
    __weak typeof(self) weakSelf = self;
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note)
     {
         [weakSelf.view addGestureRecognizer:singleTapGR];
     }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note)
     {
         [weakSelf.view removeGestureRecognizer:singleTapGR];
     }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer
{
    [self.view endEditing:YES];
}


- (void)configNavigationLeftItemWithImage:(UIImage *)image
{
    UIImage *leftImage = [UIImage imageNamed:@"back_icon"];
    if(image)
    {
        leftImage = image;
    }

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(leftBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:leftImage forState:UIControlStateNormal];
    [btn setImage:leftImage forState:UIControlStateHighlighted];
    btn.size = btn.currentImage.size;
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
   
}
- (void)configNavigationLeftItemWithTitle:(NSString *)title
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(leftBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle: title forState:UIControlStateNormal];
    [btn setTitleColor:AppTextColor forState:UIControlStateNormal];
    [btn setTitleColor:UIColor.lightGrayColor forState:UIControlStateHighlighted];
    btn.size = btn.currentImage.size;
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
}


- (void)configNavigationRightItemWithImage:(UIImage *)image
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(rightBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:image forState:UIControlStateNormal];
    [btn setImage:image forState:UIControlStateHighlighted];
    btn.size = btn.currentImage.size;
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}

- (void)configNavigationRightItmeWithTitle:(NSString *)title titleColor:(UIColor *)titleColor font:(UIFont *)font
{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:title forState:UIControlStateNormal];
    [rightButton sizeToFit];
    [rightButton.titleLabel setFont:font];
    
    [rightButton addTarget:self action:@selector(rightBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitleColor:titleColor forState:UIControlStateNormal];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}


- (void)leftBarButtonAction:(id)sender
{
    if(self.navigationController.viewControllers.count > 1)
    {
        if(self.isNeedPopToRoot){
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)rightBarButtonAction:(id)sender
{
    
}

- (BOOL)userIsLogin{
    if(![EJSUserTokenModel userTokenModel]){
        EJSLoginViewController *loginVC = [[EJSLoginViewController alloc] initWithNibName:@"EJSLoginViewController" bundle:nil];
        FlyNavigationController *nav = [[FlyNavigationController alloc] initWithRootViewController:loginVC];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nav animated:YES completion:nil];
        return NO;
    }
    return YES;
}

- (NSMutableArray *)dataSource
{
    if(!_dataSource)
    {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}


- (void)showLoadingViewWithText:(NSString *)loadingText
{
    [self hideLoadingView];
}

- (void)showLoadingInView:(UIView *)view
{
    [self hideLoadingView];
    if(!view)
    {
        [self creatLoadingImageViewInView:self.view];
        return;
    }
    [self creatLoadingImageViewInView:view];
}

- (void)hideLoadingView
{
    _loadingView.hidden = YES;
    [_loadingImgView stopAnimating];
    [_loadingImgView removeFromSuperview];
    [_loadingView removeFromSuperview];
    _loadingView = nil;
    _loadingImgView = nil;
}

- (void)showTipViewWithText:(NSString *)tipText
{
    [self hideLoadingView];
//    [self creatLoadingViewWithShowLoadingImgView:NO loadingText:tipText];
//    [self performSelector:@selector(hideLoadingView) withObject:nil afterDelay:1.5];
}

- (void)showErrorTipView:(NSString *)text
{
    [self hideLoadingView];
    [self creatErrorViewWithText:text];
}

- (void)creatErrorViewWithText:(NSString *)loadingText
{
    
    _loadingView = [[UIView alloc] initWithFrame:self.view.bounds];
//    _loadingView.backgroundColor = kCBGColor;
    [self.view addSubview:_loadingView];
    
    _loadingImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"com_pic_error"]];
    [_loadingImgView sizeToFit];
    [_loadingView addSubview:_loadingImgView];
    
    _loadingLabel = [[UILabel alloc] init];
//    _loadingLabel.textColor = kCB2Color;
    _loadingLabel.font = [UIFont systemFontOfSize:14.0];
    _loadingLabel.text = loadingText;
    [_loadingLabel sizeToFit];
    [_loadingView addSubview:_loadingLabel];
    
    [_loadingImgView layoutParentHorizontalCenter];
    [_loadingLabel layoutParentHorizontalCenter];
    _loadingImgView.top = self.view.height/2 - _loadingImgView.height/2 - 30;
    _loadingLabel.top = _loadingImgView.bottom + 30;
}

- (void)creatLoadingImageViewInView:(UIView *)loadingView
{
    
     _loadingImgView = [[UIImageView alloc] init];
    [loadingView addSubview:_loadingImgView];
    
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (int i = 1; i <= 50; i++)
    {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"com_pic_loading%i", i]];
        [refreshingImages addObject:image];
    }
    UIImage *image = [refreshingImages firstObject];
    _loadingImgView.width = image.size.width;
    _loadingImgView.height = image.size.height;
    _loadingImgView.animationImages = refreshingImages;
    _loadingImgView.animationDuration = 1.5;
    [_loadingImgView layoutParentVerticalCenter];
    [_loadingImgView layoutParentHorizontalCenter];
    [_loadingImgView startAnimating];
}

- (IBAction)contactService:(id)sender
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"0571-86339798" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"呼叫", nil];
    [alertView showWithCompletionHandler:^(NSInteger buttonIndex) {
        if(buttonIndex == 1)
        {
            NSURL *telUrl = [NSURL URLWithString:@"tel://0571-86339798"];
            if ([[UIApplication sharedApplication] canOpenURL:telUrl])
            {
                [[UIApplication sharedApplication] openURL:telUrl];
            }
        }
    }];
}

- (void)showTipMsg:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)showToastMsg:(NSString*)msg
{
    if(msg && msg.length > 0)
    {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        // Configure for text only and offset down
        hud.mode = MBProgressHUDModeText;
        hud.label.text = msg;
        hud.margin = 10.f;
        hud.label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.0];
        hud.removeFromSuperViewOnHide = YES;
        [hud showAnimated:YES];
        [hud hideAnimated:YES afterDelay:1];
    }
}
//判断是否有中文
-(BOOL)IsChinese:(NSString *)str
{
    for(int i=0; i< [str length];i++)
    {
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}

-(void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
    SEL selector = NSSelectorFromString(@"_alertController");
    if ([actionSheet respondsToSelector:selector])//ios8 以后采用UIAlertController来代替uiactionsheet和UIAlertView
    {
        UIAlertController *alertController = [actionSheet valueForKey:@"_alertController"];
        if ([alertController isKindOfClass:[UIAlertController class]])
        {
            alertController.view.tintColor = [UIColor blackColor];
        }
    }
    else//ios7 之前采用这样的方式
    {
        for( UIView * subView in actionSheet.subviews )
        {
            if( [subView isKindOfClass:[UIButton class]] )
            {
                UIButton * btn = (UIButton*)subView;
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                
            }
        }
    }
}

- (void)showNoDataViewWithText:(NSString *)text
{
    [self showNoDataViewWithText:text offset:0];
}

- (void)showNoDataViewWithText:(NSString *)text offset:(CGFloat)offset
{
    [self hideNoDataView];
    
    _noDataView = [[UIView alloc] initWithFrame:self.view.bounds];
    _noDataView.userInteractionEnabled = NO;
    _noDataView.backgroundColor = kClearColor;
    [self.view addSubview:_noDataView];
    
    NSString *noDataMsg = text?text:@"暂无数据";
    
    UILabel *textLabel = [[UILabel alloc] init];
    textLabel.textColor = UIColorFromRGB(0xA4A4A4);
    textLabel.font = kSystemFontSize(15);
    textLabel.text = noDataMsg;
    [_noDataView addSubview:textLabel];
    
    [textLabel sizeToFit];
    textLabel.center = _noDataView.center;
    textLabel.top += offset/2;
    if (textLabel.bottom + 20 > self.view.height)
    {
        textLabel.bottom = self.view.height - 20;
    }
    
    if (textLabel.top - 20 < 0)
    {
        textLabel.top = 20;
    }
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"无数据"];
    [imageView sizeToFit];
    imageView.center = _noDataView.center;
    imageView.bottom = textLabel.top - 10;
    [_noDataView addSubview:imageView];
}

- (void)hideNoDataView
{
    if(_noDataView)
    {
        [_noDataView removeFromSuperview];
        _noDataView = nil;
    }
}

@end
